﻿using System;
using System.IO;
using System.Text;



namespace Crm2011.Framework.Core
{
    public static class FileEncoding
    {
        /// <summary>
        /// File (UTC) to Base64
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <returns></returns>
        public static string GetEncodedFileContents(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] binaryData = new byte[fs.Length];
            long bytesRead = fs.Read(binaryData, 0, (int) fs.Length);
            fs.Close();
            return Convert.ToBase64String(binaryData, 0, binaryData.Length);
        }



        /// <summary>
        /// This method will Decode a Base64 string.
        /// </summary>
        /// <param name="enc">The enc.</param>
        /// <returns>
        /// A String containing the results of decoding the
        /// specified sequence of bytes.
        /// </returns>
        public static string DecodeFrom64(string enc)
        {
            // Here's your problem. You have an additional, invisible character at the beginning of the String: 
            // fileformat.info/info/unicode/char/feff/index.htm. It's a byte order mark
            // (en.wikipedia.org/wiki/Byte_order_mark) – JB Nizet Jul 6 '12 at 17:05
            // http://stackoverflow.com/questions/11366257/numberformatexception-on-valid-number-string
            byte[] encodedDataAsBytes = Convert.FromBase64String(enc);
            string result = Encoding.UTF8.GetString(encodedDataAsBytes);
            return (int) result[0] == 0xFEFF ? result.Substring(1) : result;
        }
    }
}